import React, { Component } from 'react'
import SourceTable from '../common/sourceTable'
import { Card, Button, message, Popconfirm } from "antd"
import { EditFilled, DeleteFilled } from "@ant-design/icons"
import { FormInstance } from "antd/lib/form"
import { getGoodInsInfo, editGoodIns, addGoodIns, delGoodIns } from '@net/good/inspection'
import { getSgsInfo } from "@net/company/sgs"
import HeaderSearch from '../common/headerSearch'
import Modal from '@comp/Modal/index'
import DialogForm from '../common/dialogForm'
import "../../index.scss"
import Power from '@comm/power'
import DialogTable from '../common/dialogTable'
import { getGoodPro } from '@net/good/product'
import moment from 'moment'
import {getConInvalid} from '@comm/utils'

interface IProps { }
interface IStates {
    dataSource: any[],
    loading: boolean,
    visible: boolean,
    popVisible: string,
    title: string,
    Id: number,
    isEdit: boolean,
    page: number,
    pageSize: number,
    total: number,
    diaTabDataFn: any[],
    diaVisbleFn: boolean,
    diaTabDataSu: any[],
    diaVisbleSu: boolean,
    diaTable: string,
    search: any,
    pId:number,
    editItem:any,
}
export default class GoodSource extends Component<IProps, IStates> {
    private dialogFormRef: any = React.createRef<FormInstance>()
    constructor(props: any) {
        super(props)
        this.state = {
            dataSource: [],
            loading: true,
            visible: false,
            popVisible: "-1",
            title: "",
            Id: 0,
            isEdit: false,
            total: 0,
            page: 1,
            pageSize: 5,
            diaTabDataFn: [],
            diaVisbleFn: false,
            diaTabDataSu: [],
            diaVisbleSu: false,
            diaTable: "",
            search: null,
            pId:0,
            editItem:{}
        }
    }
    // 表格设置
    private columns = [
        {
            title: "操作",
            dataIndex: "do",
            align: "center",
            fixed:"left",
            render: (text: any, record: any) => {
                const item = record
                return (
                    <div className="do">
                        <Power authKey="good:ins:update">
                            <Button size="small" type="primary" icon={<EditFilled />} onClick={() => { this.openEditDialog(item) }} />
                        </Power>
                        <Power authKey="good:ins:remove">
                            <Popconfirm title="您确定要删除吗？" okText="是" cancelText="否"
                                onConfirm={this.delete} visible={item.key === this.state.popVisible}
                                onCancel={() => { this.setState({ popVisible: "-1" }) }}>
                                <Button size="small" danger icon={<DeleteFilled />} onClick={() => { this.openPopConfirm(item) }} />
                            </Popconfirm>
                        </Power>
                    </div>
                )
            }
        },
        {
            title: "名称",
            dataIndex: "insName",
            align: "center",
            fixed: "left"
        },
        {
            title: "质量审核",
            dataIndex: "insVerify",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" danger>未通过</Button>
                } else if (text === "1") {
                    return text = <Button type="link">审核通过</Button>
                } else {
                    return text = <Button type="link" className="agree">待审核</Button>
                }
            },
            fixed: "left"
        },
        {
            title: "有无气味",
            dataIndex: "insSmell",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" >无</Button>
                } else if (text === "1") {
                    return text = <Button type="link" danger>有</Button>
                } else {
                    return text = <Button type="link" className="agree">其它</Button>
                }
            }
        },
        {
            title: "有无杂质",
            dataIndex: "insImpurity",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" >无</Button>
                } else if (text === "1") {
                    return text = <Button type="link" danger>有</Button>
                } else {
                    return text = <Button type="link" className="agree">其它</Button>
                }
            }
        },
        {
            title: "成分含量",
            dataIndex: "insComposition",
            align: "center",
            ellipsis:true
        },
        {
            title: "重金属",
            dataIndex: "insHeavyMetal",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" danger>无</Button>
                } else if (text === "1") {
                    return text = <Button type="link">有</Button>
                } else {
                    return text = <Button type="link" className="agree">其它</Button>
                }
            }
        },
        {
            title: "生物指标(菌落)",
            dataIndex: "insBiomarker",
            align: "center",
            ellipsis:true
        },
        {
            title: "有毒物质",
            dataIndex: "insToxicSub",
            align: "center"
        },
        {
            title: "检测人员",
            dataIndex: "insPerson",
            align: "center"
        },
        {
            title: "检测机构",
            dataIndex: "insCompany",
            align: "center",
            ellipsis:true
        },
        {
            title: "检测时间",
            dataIndex: "insCreatetime",
            align: "center"
        },
        {
            title: "备注(原因)",
            dataIndex: "insRemark",
            align: "center",
            ellipsis:true
        }
    ]
    private columnDiaFn = [
        {
            key: "name",
            dataIndex: "name",
            title: "名称",
            align: "center"
        },
        {
            key: "environment",
            dataIndex: "environment",
            title: "生产环境",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" danger>不达标</Button>
                } else if (text === "1") {
                    return text = <Button type="link">达标</Button>
                }
            }
        },
        {
            key: "period",
            dataIndex: "period",
            title: "生产周期/月",
            align: "center"
        },
        {
            key: "amount",
            dataIndex: "amount",
            title: "生产数量/个",
            align: "center"
        },
        {
            key: "date",
            dataIndex: "date",
            title: "生产日期",
            align: "center"
        },
        {
            key: "qgp",
            dataIndex: "qgp",
            title: "保质期",
            align: "center"
        }
    ]
    private columnDiaSu = [
        {
            dataIndex: "sgsName",
            title: "名称",
            align: "center"
        },
        {
            dataIndex: "sgsLeader",
            title: "负责人",
            align: "center"
        },
        {
            dataIndex: "sgsPhone",
            title: "联系电话",
            align: "center"
        },
        {
            dataIndex: "sgsPlace",
            title: "地址",
            align: "center",
        },
        {
            dataIndex: "sgsConStart",
            title: "合同生效时间",
            align: "center"
        },
        {
            dataIndex: "sgsConEnd",
            title: "合同失效时间",
            align: "center"
        },
    ]
    // 弹窗表单设置
    private dialogFormColumn = () => {
        return [
            {
                type: 'input',
                label: "食品名称",
                name: "insName",
                rules: [
                    { required: true, message: "请输入名称" }
                ],
                component: {
                    placeholder: "请输入名称",
                    disabled:this.state.isEdit
                },
                style: { borderRadius: "5px" },
                id: "specName",
                onFocus: () => this.openDiaTable("fn"),
            },
            {
                type: 'select',
                label: "气味",
                name: "insSmell",
                component: {
                    placeholder: "是否有气味"
                },
                option: [
                    { key: "0", value: "无" },
                    { key: "1", value: "有" }
                ],
                style: { borderRadius: "5px" }
            },
            {
                type: 'select',
                label: "杂质",
                name: "insImpurity",
                component: {
                    placeholder: "是否有杂质"
                },
                option: [
                    { key: "0", value: "无" },
                    { key: "1", value: "有" },
                ],
                style: { borderRadius: "5px" }
            },
            {
                type: 'textarea',
                label: "成分含量",
                name: "insComposition",
                component: {
                    placeholder: "请输入该食品的成分含量"
                },
                rules: [
                    { required: true, message: "请输入该食品的成分含量" }
                ],
                style: { borderRadius: "5px" }
            },
            {
                type: 'select',
                label: "重金属",
                name: "insHeavyMetal",
                component: {
                    placeholder: "是否含有重金属"
                },
                option: [
                    { key: "0", value: "无" },
                    { key: "1", value: "有" },
                ],
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "生物指标(菌落)",
                name: "insBiomarker",
                component: {
                    placeholder: "请输入生物指标"
                },
                style: { borderRadius: "5px" },
            },
            {
                type: 'input',
                label: "有毒物质",
                name: "insToxicSub",
                component: {
                    placeholder: "是否有有害物质"
                },
                style: { borderRadius: "5px" },
            },
            {
                type: 'input',
                label: "检测机构",
                name: "insCompany",
                component: {
                    placeholder: "请选择检测机构"
                },
                style: { borderRadius: "5px" },
                id: "specsgsName",
                onFocus: () => this.openDiaTable("su")
            },
            {
                type: 'input',
                label: "检测人员",
                name: "insPerson",
                component: {
                    placeholder: "请输入检测人员"
                },
                rules: [
                    { required: true, message: "请输入检测人员" }
                ],
                style: { borderRadius: "5px" },
            },
            {
                type: 'datePicker',
                label: "检测时间",
                name: "insCreatetime",
                component: {
                    placeholder: "请输入检测时间"
                },
                rules: [
                    { required: true, message: "请输入检测时间" }
                ],
                style: { borderRadius: "5px" },
            },
            {
                type: 'select',
                label: "质量审核",
                name: "insVerify",
                component: {
                    placeholder: "该食品质量是否过关",
                    disabled:this.state.editItem.insVerify === '1' ? true : false
                },
                rules: [
                    { required: true, message: "该食品质量是否过关" }
                ],
                option: [
                    { key: "0", value: "未通过" },
                    { key: "1", value: "审核通过" },
                    { key: "2", value: "待审核" },
                ],
                style: { borderRadius: "5px" }
            },
            {
                type: 'textarea',
                label: "备注",
                name: "insRemark",
                component: {
                    placeholder: "可备注食品存在的问题或是质量未通过的原因"
                },
                style: { borderRadius: "5px" }
            },

        ]
    }
    private searchCol = [
        {
            type: 'input',
            name: "fname",
            label: "食品名称",
            component: {
                placeholder: "请输入食品名称",
            },
            style: { borderRadius: "5px" }
        },
        {
            type: 'select',
            name: "fverify",
            label: "审核状态",
            option:[
                {value:"未通过",key:"0"},
                {value:"通过",key:"1"},
                {value:"待审核",key:"2"},
            ],
            component: {
                placeholder: "请选择审核状态",
            },
            style: { borderRadius: "5px",width:"200px" }
        },
        {
            type: 'datePicker',
            name: "insTime",
            label: "检测时间",
            component: {
                placeholder: "请选择检测时间",
            },
            style: { borderRadius: "5px" }
        },
    ]
    public componentDidMount() {
        this.getInfo(1, 5)
    }
    public getInfo = (page: number, pageSize: number) => {
        getGoodInsInfo({ page, pageSize }, this.state.search).then((res: any) => {
            res.data.data.forEach((item: any) => {
                item.key = item.Id
            })
            this.setState({
                loading: false,
                dataSource: res.data.data,
                total: res.data.total
            })
        })
    }
    // 页码切换监听事件
    public pageChange = (page: number, pageSize?: number) => {
        if (pageSize) {
            this.setState({ page, pageSize }, () => {
                this.getInfo(this.state.page, this.state.pageSize)
            })
        }
    }
    public search =  (item: any) => {
        if (item.fname === undefined && item.fverify === undefined && item.insTime === undefined) {
            this.setState({ search: null }, () => {
                this.getInfo(this.state.page, this.state.pageSize)
            })
            return
        }
        item.insTime = moment(item.insTime).format("YYYY/MM/DD")
        this.setState({ search: item }, async() => {
            const res = await getGoodInsInfo({ page: 1, pageSize: 5 }, this.state.search)
            const { status, msg, data, total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ dataSource: data, total })
            }
        })
    }
    // 弹框表格页码切换监听事件
    public pageDiaChange = (page?: number, pageSize?: number) => {
        if (this.state.diaTable === "fn") {
            if (pageSize && page) {
                getGoodPro({ page, pageSize }).then((res: any) => {
                    res.data.data.forEach((item: any) => {
                        item.key = item.code
                    })
                    this.setState({ diaTabDataFn: res.data.data, total: res.data.total })
                })
            }
        }
        if (this.state.diaTable === 'su') {
            if (pageSize && page) {
                getSgsInfo({ page, pageSize }).then((res: any) => {
                    res.data.data.forEach((item: any) => {
                        item.key = item.code
                    })
                    this.setState({ diaTabDataSu: res.data.data, total: res.data.total })
                })
            }
        }
    }
    // table弹框搜索
    public diaSearch = async (name?: string) => {
        let res: any
        if (this.state.diaTable === "fn") {
            name === "" ?
                res = await getGoodPro({ page: 1, pageSize: 5 })
                :
                res = await getGoodPro({ page: 1, pageSize: 1 },name)
            const { status, msg, data, total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ diaTabDataFn: data, total })
            }
        }
        if (this.state.diaTable === "su") {
            name === "" ?
                res = await getSgsInfo({ page: 1, pageSize: 5 })
                :
                res = await getSgsInfo({ page: 1, pageSize: 1 }, name)
            const { status, msg, data,total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ diaTabDataSu: data,total })
            }
        }

    }
    public selectRowFn = (item: any) => {
        if(item.environment === '0'){
            message.warn({content:'该食品生产未达标',style:{marginTop:"20%"}})
            return
        }
        this.dialogFormRef.current.setFieldsValue({ insName: item.name })
        this.setState({ diaVisbleFn: false,pId:item.Id })
    }
    public selectRowSu = (item: any) => {
        let invalid = getConInvalid(item.sgsConStart,item.sgsConEnd)
        if(!invalid){
            message.warn({ content: '合同已失效', style: { marginTop: "20%" } })
            return
        }
        this.dialogFormRef.current.setFieldsValue({ insCompany: item.sgsName })
        this.setState({ diaVisbleSu: false })
    }
    public getDiaContent = (item: string) => {
        if (item === "fn") {
            return (
                <DialogTable
                    columns={this.columnDiaFn}
                    dataSource={this.state.diaTabDataFn}
                    pageChange={this.pageDiaChange}
                    total={this.state.total}
                    scroll={{ x: 1200 }}
                    selectRow={this.selectRowFn}
                    search={this.diaSearch}>
                </DialogTable>
            )
        }
        if (item === "su") {
            return (
                <DialogTable
                    columns={this.columnDiaSu}
                    dataSource={this.state.diaTabDataSu}
                    pageChange={this.pageDiaChange}
                    total={this.state.total}
                    scroll={{ x: 1200 }}
                    selectRow={this.selectRowSu}
                    search={this.diaSearch}
                    label="检测机构名称"
                    placeholder="请输入检测机构名称">
                </DialogTable>
            )
        }
    }
    public renderDiaTab = (item: string) => {
        if (item === "fn") {
            return (<Modal
                title="选择食品"
                visible={this.state.diaVisbleFn}
                content={this.getDiaContent(this.state.diaTable)}
                width="1000px"
                onCancel={() => { this.setState({ diaVisbleFn: false }) }}
            />
            )
        }
        if (item === "su") {
            return (<Modal
                title="选择检测机构"
                visible={this.state.diaVisbleSu}
                content={this.getDiaContent(this.state.diaTable)}
                width="1000px"
                onCancel={() => { this.setState({ diaVisbleSu: false }) }}
            />
            )
        }
    }
    // 打开添加弹框
    public openDialog = () => {
        this.setState({
            visible: true,
            title: "质量检测信息添加",
            isEdit: false,
            editItem:{}
        }, () => {
            this.renderModal(this.state.title)
        })
    }
    // 打开编辑弹框
    public openEditDialog = (item: any) => {
        this.setState({
            visible: true,
            title: "质量检测信息编辑",
            Id: item.Id,
            isEdit: true,
            editItem:item
        }, () => {
            this.renderModal(this.state.title)
            item.insCreatetime = moment(item.insCreatetime, 'YYYY/MM/DD')
            this.dialogFormRef.current.setFieldsValue(item)

        })
    }
    // 打开选择货物弹框
    public openDiaTable = (item: string) => {
        this.setState({ diaTable: item })
        if (item === "fn") {
            this.setState({ diaVisbleFn: true }, () => {
                this.pageDiaChange(1, 5)
            })
        }
        if (item === "su") {
            this.setState({ diaVisbleSu: true }, () => {
                this.pageDiaChange(1, 5)
            })
        }
    }
    public getContent = () => {
        return (
            <DialogForm ref={this.dialogFormRef} column={this.dialogFormColumn()} go={this.openDialog}>
            </DialogForm>
        )
    }
    // 提交表单数据
    public onOk = () => {
        this.dialogFormRef.current.validateFields(this.add())
    }
    // 编辑
    public onEdit = () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.Id = this.state.Id
        values.pId = this.state.pId
        values.insCreatetime = moment(values.insCreatetime).format("YYYY/MM/DD")
        // console.log(values)
        editGoodIns(values).then(res => {
            const { msg, status } = res.data
            // console.log(res)
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.onCancel()
                this.dialogFormRef.current.resetFields()
            }
        })
    }
    // 添加
    public add = () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.pId = this.state.pId
        values.insCreatetime = moment(values.insCreatetime).format("YYYY/MM/DD")
        addGoodIns(values).then(res => {
            const { msg, status } = res.data
            // console.log(res)
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.onCancel()
                this.dialogFormRef.current.resetFields()
            }
        })
    }
    // 打开气泡确认框
    public openPopConfirm = (item: any) => {
        this.setState({ Id: item.Id, popVisible: item.key })
    }
    // 删除
    public delete = () => {
        delGoodIns(this.state.Id).then(res => {
            const { msg, status } = res.data
            // console.log(res)
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
            }
            this.getInfo(this.state.page, this.state.pageSize)
        })
        setTimeout(() => {
            this.setState({ popVisible: "-1" })
        }, 1000)
    }
    // 关闭弹窗
    public onCancel = () => {
        this.setState({ visible: false, isEdit: false })
        this.dialogFormRef.current.resetFields()
        this.getInfo(this.state.page, this.state.pageSize)
    }
    public renderButton() {
        return (
            <div>
                <Power authKey="good:ins:save">
                    <Button type="primary" onClick={() => { this.openDialog() }}>新增质量检测</Button>
                </Power>
            </div>
        )
    }
    public renderModal = (item?: string) => {
        return (
            <Modal
                title={this.state.title}
                visible={this.state.visible}
                content={this.getContent()}
                width="1000px"
                onOk={item === "" ? this.onEdit : this.onOk}
                onCancel={this.onCancel}>
            </Modal>
        )
    }
    public render() {
        return (
            <div className="source">
                <Card className="card">
                    <HeaderSearch
                        authKey="good:ins:list"
                        column={this.searchCol}
                        search={this.search}></HeaderSearch>

                    {this.renderButton()}
                    <SourceTable
                        columns={this.columns}
                        dataSource={this.state.dataSource}
                        loading={this.state.loading}
                        tableKey="goodSourceTable"
                        pageChange={this.pageChange}
                        total={this.state.total}
                        scroll={{ x: 1700 }}
                    >
                    </SourceTable>
                </Card>
                {this.state.title === "质量检测信息添加" ? this.renderModal() : this.renderModal("")}
                {this.renderDiaTab("fn")}
                {this.renderDiaTab("su")}
            </div>
        )
    }

}